package cz.tomasdvorak.cars.pages.signing;

import cz.tomasdvorak.cars.auth.MyAuthenticatedWebSession;
import cz.tomasdvorak.cars.dto.AppLocale;
import cz.tomasdvorak.cars.dto.User;
import cz.tomasdvorak.cars.pages.user.EditUserPage;
import cz.tomasdvorak.cars.utils.Lists;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.ResourceModel;

import java.util.Locale;

public class UtilitiesPanel extends Panel {

    public UtilitiesPanel(String id) {
        super(id);
        final MyAuthenticatedWebSession session = (MyAuthenticatedWebSession) getSession();
        Link link = new Link("loginLink") {
            public void onClick() {
                if (session.isSignedIn()) {
                    getSession().invalidate();
                    setResponsePage(SignOutPage.class);
                } else {
                    setResponsePage(SignInPage.class);
                }
            }
        };
        link.add(new Label("actionName", new ResourceModel(session.isSignedIn() ? "logout" : "login")));
        add(link);
        Link editUserLink = new Link("editUserLink") {
            public void onClick() {
                setResponsePage(new EditUserPage(new Model<User>(session.getUser())));
            }
        };
        editUserLink.add(new Label("username", session.isSignedIn() ? session.getUser().getName() : ""));
        editUserLink.setVisible(session.isSignedIn());
        add(editUserLink);

        add(new ListView<AppLocale>("locale", Lists.arrayList(AppLocale.values())){

            protected void populateItem(final ListItem<AppLocale> appLocaleListItem) {
                Link link = new Link("localeLink") {
                    public void onClick() {
                        getSession().setLocale(new Locale(
                                appLocaleListItem.getModelObject().name()));
                        setResponsePage(getApplication().getHomePage());
                    }
                };
                link.add(new Label("localeName", new ResourceModel("locale." + appLocaleListItem.getModelObject().name())));
                appLocaleListItem.add(link);
            }
        });
    }
}
